var {isInPolygon, getSideLen, getDeg, isInCircle} = require('helper')
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        img: String,
        mode: {
            type: String,
            value: 'widthFix', // 只支持 aspectFill, widthFix, heightFix
        },
        hrefAreas: Object,
        noHrefAreas: Object,
        hrefAreaColor: {
            type: String,
            value: '#fff'
        },
        noHrefAreaColor: {
            type: String,
            value: 'red'
        },
        img: String,
        debug: {
            type: Boolean,
            value: false
        },
        showArea: {
            type: Boolean,
            value: true
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        imgSrc: '',
        mapHrefAreas: {},
        mapNoHrefAreas: {},
    },
    observers: {
        mode: async function (m) {
            var t = this
            if (!m) return;
            await t.init()
            t.initQuery()
        },
        img: function (m) {
            let t = this
            if (!m) return;
            t.imgOWidth = 0
            t.imgOheight = 0
            t.init()
        },
        hrefAreaColor: function (m) {
            let t = this
            if (!m) return;
            t.setData({
                hrefColor: m
            })
        },
        noHrefAreaColor: function (m) {
            let t = this
            if (!m) return;
            t.setData({
                noHrefColor: m
            })
        }
    },
    lifetimes: {
        attached() {
            var t = this
            t.imgOWidth = 0
            t.imgOheight = 0
            t.init()
        }
    },
    /**
     * 组件的方法列表
     */
    methods: {
        async init() {
            let t = this
            t.setData({
                imgSrc: t.data.img,
                mapHrefAreas: t.data.hrefAreas,
                mapNoHrefAreas: t.data.noHrefAreas,
                hrefColor: t.data.hrefAreaColor,
                noHrefColor: t.data.noHrefAreaColor,
                imgMode: t.data.mode in {aspectFill: 0, widthFix: 0, heightFix: 0} ? t.data.mode : 'widthFix'
            })
            t.img = {}
            t.hrefAreas = []
            t.noHrefAreas = []
            t.target = {}

            return Promise.resolve()
        },
        initQuery() {
            var t = this
            wx.createSelectorQuery().in(t).selectAll('#maparea-img,.nohref-area,.href-area').boundingClientRect(function (res) {
                for (var i in res) {
                    if (!t.img.id && res[i].id === 'maparea-img') {
                        t.img.top = res[i].top
                        t.img.left = res[i].left
                        t.img.width = res[i].width
                        t.img.height = res[i].height
                        t.img.dataset = res[i].dataset
                        t.img.id = res[i].id
                        t.imgOWidth > 0 && (t.img.oWidth = t.imgOWidth)
                        t.imgOheight > 0 && (t.img.oHeight = t.imgOheight)

                        t.img.xScale = t.img.width / t.img.oWidth
                        t.img.yScale = t.img.height / t.img.oHeight
                        // console.log(t.img)
                        t.initScale(-1)
                    } else if (res[i].dataset.nohref) {
                        t.noHrefAreas.push(res[i])
                    } else {
                        t.hrefAreas.push(res[i])
                    }
                }
            }).exec()
        },
        initPolyOffset(key, index) {
            let t = this, polys = t.data[key].poly || [];
            console.info('polys:', polys)
            for (let i in polys) {
                let x = 0, y = 0, w = 0, h = 0, xs = [], ys = [], polyLines = [], tmpx = [], tmpy = [], maxVal = 0
                // console.log(polys[i].coords)
                for (let k in polys[i].coords) {
                    polys[i].coords[k].x = polys[i].coords[k].x
                    polys[i].coords[k].y = polys[i].coords[k].y
                    xs.push(polys[i].coords[k].x)
                    ys.push(polys[i].coords[k].y)

                    let nextK = parseInt(k) + 1 >= parseInt(polys[i].coords.length) ? 0 : parseInt(k) + 1,
                        oneLineX = polys[i].coords[k].x,
                        oneLineY = polys[i].coords[k].y, oneLine = {}
                    oneLine = {
                        p1: {x: polys[i].coords[k].x, y: polys[i].coords[k].y},
                        p2: {x: polys[i].coords[nextK].x, y: polys[i].coords[nextK].y}
                    }

                    let sameX = polys[i].coords[k].x === polys[i].coords[nextK].x,
                        sameY = polys[i].coords[k].y === polys[i].coords[nextK].y,
                        cLen = getSideLen(oneLine.p1, oneLine.p2),
                        deg = getDeg(oneLine.p1, oneLine.p2)

                    oneLine.x = oneLineX
                    oneLine.y = oneLineY
                    oneLine.sameX = sameX
                    oneLine.sameY = sameY
                    oneLine.cLen = cLen
                    oneLine.deg = deg
                    polyLines.push(oneLine)
                }
                tmpx = xs.sort((a, b) => a - b)
                x = tmpx.shift()
                maxVal = tmpx.pop()
                w = maxVal - x

                tmpy = ys.sort((a, b) => a - b)
                y = tmpy.shift()
                let tmpVal = tmpy.pop()
                h = tmpVal - y
                polys[i].maxVal = tmpVal > maxVal ? tmpVal : maxVal
                polys[i].offset = {x, y, w, h}
                const color = index === polys[i].param.index ? '#FF004A' :  t.data.hrefColor;
                let border = key === 'mapNoHrefAreas' ? (t.data.debug ? '2px dashed ' + t.data.noHrefColor : 'none') : (t.data.debug ? '2px dashed ' + color : 'none')
                for (let o in polyLines) {
                    polyLines[o].style = 'top:' + ((polyLines[o].y - y) * t.img.yScale) + 'px;left:' + ((polyLines[o].x - x) * t.img.xScale) + 'px;' + (polyLines[o].sameX || polyLines[o].sameY ? (
                        polyLines[o].sameX ? 'height:' + (polyLines[o].cLen * t.img.yScale) + 'px;width:1px;border-left: ' + border + ';' : 'width:' + (polyLines[o].cLen * t.img.xScale) + 'px;height:1px;border-bottom: ' + border + ';'
                    ) : 'width:' + (polyLines[o].cLen * t.img.xScale) + 'px;height:1px;border-bottom: ' + border + ';-webkit-transform:rotate(' + polyLines[o].deg + 'deg);-moz-transform:rotate(' + polyLines[o].deg + 'deg);')
                }
                polys[i].polyLines = polyLines
            }

            return polys
        },
        imgLoad(e) {
            let t = this
            t.img.oHeight = e.detail.height
            t.img.oWidth = e.detail.width
            t.imgOWidth = e.detail.width
            t.imgOheight = e.detail.height
            t.img.mode = e.target.dataset.mode
            setTimeout(() => {
                t.initQuery()
            }, 1000)
        },

        initScale(index) {
            let t = this, polys = t.initPolyOffset('mapHrefAreas', index),
                noPolys = t.initPolyOffset('mapNoHrefAreas')
            t.setData({
                xScale: t.img.xScale,
                yScale: t.img.yScale,
                ['mapHrefAreas.poly']: polys,
                ['mapNoHrefAreas.poly']: noPolys,
            })
        },

        /**
         * 判断是否在区域内
         * @param  p oject {x, y} 点坐标
         * @param  type string 区域类型，href或者nohref，默认href
         */
        isInArea(p, type = 'href') {
            let t = this, flag = !1, flag2 = !1,
                areas = JSON.parse(JSON.stringify(type === 'href' ? t.hrefAreas : t.noHrefAreas))
            if (type === 'href' && t.target.dataset && t.target.dataset.shape) {
                t.target = {}
            }
            for (var i in areas) {
                if (areas[i].dataset.shape === 'circle') {
                    var _op = {x: areas[i].dataset.coords.x * t.img.xScale, y: areas[i].dataset.coords.y * t.img.yScale}
                    flag = isInCircle(p, _op, areas[i].dataset.r * ((t.img.yScale + t.img.xScale) / 2))
                    type === 'href' && flag && (t.target = areas[i])
                    if (flag) break;
                } else if (areas[i].dataset.shape === 'rect' || areas[i].dataset.shape === 'poly') {
                    var crds = []
                    if (areas[i].dataset.shape === 'rect') {
                        crds.push(areas[i].dataset.coords[0])
                        crds.push({x: areas[i].dataset.coords[0].x, y: areas[i].dataset.coords[1].y})
                        crds.push(areas[i].dataset.coords[1])
                        crds.push({x: areas[i].dataset.coords[1].x, y: areas[i].dataset.coords[0].y})
                    } else {
                        crds = areas[i].dataset.coords
                    }
                    for (var ii in crds) {
                        crds[ii].x = crds[ii].x * t.img.xScale
                        crds[ii].y = crds[ii].y * t.img.yScale
                    }
                    flag = isInPolygon(p, crds)
                    type === 'href' && flag && (t.target = areas[i])
                    if (flag) break;
                }
            }
            type === 'href' && (flag2 = t.isInArea(p, 'nohref'))
            type === 'href' && flag2 && (t.target = {})
            // type ==='href' ? console.log('isInArea:', flag) : console.log('isInNoArea:', flag2)
            return type === 'href' ? (flag && !flag2 ? true : false) : (flag ? true : false)
        },
        imgtap(e) {
            var t = this, ds = e.currentTarget.dataset, p = e.detail, shape = ds.shape || '',
                coords = shape === 'circle' ? ds.coords || {} : ds.coords || [],
                isInArea = !1, isInNoArea = !1

            // _p 相对于图片的坐标
            var _p = {x: p.x - t.img.left, y: p.y - t.img.top}
            isInArea = t.isInArea(_p)
            if (isInArea) {
                const index = t.target.dataset.param.index;
                t.initScale(index);
                t.triggerEvent('inside', {
                    instance: t,
                    opoint: p,
                    point: _p,
                    param: t.target.dataset.param,
                    target: t.target
                })
            } else {
                // console.log('outside! target:', t.target)
                t.triggerEvent('outside', {instance: t, target: t.target})
            }
        }
    }
})
